package com.korion.srceencapture;

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.TypedValue;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.text.SimpleDateFormat;

/**
 * @author chenyinying
 * @date 2020/9/20
 */
public class PlayViewWrap extends HandlerThread implements SurfaceHolder.Callback {

    private SurfaceView mSurfaceView;

    private Handler myHandler;

    private boolean mReady;

    public PlayViewWrap(SurfaceView surfaceView){
        super("player");
        mSurfaceView = surfaceView;
        mSurfaceView.getHolder().addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mReady = true;
        if (getState() == State.NEW) {
            start();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mReady = false;
    }

    @Override
    protected void onLooperPrepared() {
        myHandler = new Handler(getLooper());
        myHandler.post(drawTask);
    }

    private Runnable drawTask = new Runnable() {
        int count = 0;
        Rect rect = new Rect();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        {
            paint.setTextSize(sp2px(16));
            paint.setColor(Color.BLACK);
        }
        @Override
        public void run() {
            if (mReady) {
                Surface surface = mSurfaceView.getHolder().getSurface();
                Canvas canvas = surface.lockCanvas(null);
                canvas.drawColor(Color.WHITE);
                String time = format.format(System.currentTimeMillis());
                int width = mSurfaceView.getWidth(), height = mSurfaceView.getHeight();
                paint.getTextBounds(time, 0, time.length(), rect);
                int offsetX = (width - rect.width()) / 2;
                int offsetY = (height - rect.height()) / 2 + rect.height();
                canvas.drawText(time, offsetX, offsetY, paint);

                String counter = String.valueOf(count);
                paint.getTextBounds(counter, 0, counter.length(), rect);
                canvas.drawText(counter, width - rect.width(), rect.height(), paint);
                count = (count + 1) % 10000;
                surface.unlockCanvasAndPost(canvas);
            }
            myHandler.postDelayed(this, 10);
        }
    };

    private static int sp2px(float value){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, Resources.getSystem().getDisplayMetrics());
    }
}
